package net.opentsdb.tsd;


import com.fasterxml.jackson.core.type.TypeReference;
import net.opentsdb.core.IncomingDataPoint;
import net.opentsdb.utils.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Hujf
 * @title: HttpJsonSerializer
 * @date 2021-09-24 9:17
 * @description: Implementation of the base serializer class with JSON as the format
 */
public class HttpJsonSerializer extends HttpSerializer {

    /** Type reference for incoming data points */
    static TypeReference<ArrayList<IncomingDataPoint>> TR_INCOMING =
            new TypeReference<ArrayList<IncomingDataPoint>>() {};

    /**
     * Constructor that sets the query object
     * @param query Request/resposne object
     */
    public HttpJsonSerializer(final HttpQuery query) {
        super(query);
    }


    @Override
    public <T extends IncomingDataPoint> List<T> parsePutV1(Class<T> type, TypeReference<ArrayList<T>> typeReference) {
       if(!query.hasContent()){
           throw new BadRequestException("miss ");
       }
       final String content = query.getContext().trim();
       int fristByte = content.charAt(0);
       if(fristByte == '{'){
           final T dp = (T) JSON.parseToObject(content,type);
           final ArrayList<T> dps = new ArrayList<T>(1);
           dps.add(dp);
           return dps;
       }else if( fristByte =='['){
           return JSON.parseToObject(content,typeReference);
       }else{
           throw new BadRequestException("json is not ok");
       }
    }
}
